import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, Typography, message, Alert, Spin } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { authService } from '../services/api';
import '../styles/Auth.css';

const { Title } = Typography;

const Login = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const onFinish = (values) => {
    setLoading(true);
    setError('');
    
    const loginData = {
      username: values.username,
      password: values.password
    };
    
    console.log('准备发送的登录数据:', loginData);
    
    authService.login(loginData)
      .then(response => {
        console.log('登录响应:', response);
        const { data } = response;
        if (data && data.token && data.user) {
          // 登录成功
          message.success('登录成功');
          // 保存用户信息
          localStorage.setItem('userInfo', JSON.stringify(data.user));
          // 保存token
          localStorage.setItem('token', data.token);
          // 根据用户角色跳转到不同页面
          if (data.user.role === 'ADMIN') {
            navigate('/admin'); // 管理员跳转到管理员界面
          } else {
            navigate('/'); // 普通用户跳转到首页
          }
        } else {
          setError(data.message || '登录失败，返回数据格式不正确');
        }
      })
      .catch(error => {
        console.error('登录错误详情:', error);
        if (error.response && error.response.data) {
          if (typeof error.response.data === 'string') {
            setError(error.response.data);
          } else if (error.response.data.message) {
            setError(error.response.data.message);
          } else {
            setError('登录失败，请检查用户名和密码');
          }
        } else {
          setError('网络错误，请检查服务器连接');
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return (
    <div className="auth-page">
      <div className="auth-form auth-form-large">
        <Title level={2} className="auth-form-title">用户登录</Title>
        {error && (
          <Alert
            message="登录失败"
            description={error}
            type="error"
            showIcon
            style={{ marginBottom: 24 }}
            closable
            onClose={() => setError('')}
          />
        )}
        <Form
          name="login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          layout="vertical"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
            <Link to="/forgot-password" style={{ float: 'right' }}>
              忘记密码?
            </Link>
          </Form.Item>
          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              className="auth-form-button" 
              loading={loading} 
              block
              size="large"
            >
              登录
            </Button>
          </Form.Item>
          <div style={{ textAlign: 'center', fontSize: '16px', marginTop: '16px' }}>
            还没有账号？ <Link to="/register">立即注册</Link>
          </div>
        </Form>
      </div>
    </div>
  );
};

export default Login; 